package com.entrogy.controller;


import com.entrogy.bean.*;
import com.entrogy.service.ExamService;
import com.entrogy.service.StudentService;
import com.entrogy.service.UserService;
import com.entrogy.utils.ScoreTableNameUtil;
import com.entrogy.utils.constants.ErrorEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author 罗兴江
 * @date 2019/5/31 0025 上午 10:54
 * 考试管理 控制层
 */
@RestController
@RequestMapping(value = "/exam")
@Api(description = "考试管理操作的相关接口")
public class ExamController {

    @Autowired
    private ExamService examService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserService userService;

    // 创建考试页面初始化,返回该教师创建的所有考试
    @RequestMapping(value = "/list" ,method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "教师id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "schoolCode", value = "学校id", dataType = "String", paramType = "query"),
    })
    @ApiOperation(value = "返回该教师创建的所有考试---暂不控制某个用户查看考试的范围")
    public Msg getExamList(Integer currentPage, Integer pageSize){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        int totalCount = examService.countExam(schoolCode);
        PageHelper.startPage(currentPage != null ? currentPage : 1, pageSize != null ? pageSize : 10);
        List<ExamEntity> examList = examService.findExamList(null, schoolCode, null);
        return Msg.success().add("examList", examList).add("totalCount", totalCount);
    }

    // 创建考试
    @PostMapping(value = "/add")
    @ApiOperation(value = "创建考试")
    public Msg addExam(@ModelAttribute ExamEntity examEntity){
        //生成该次考试成绩表存储的表名,存储的表名规则为exam_score+当前年份+当前月份
        Date currentTime = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        //根据日期生成表名
        String scoreTableName = ScoreTableNameUtil.createScoreTableName(dateFormat.format(currentTime));
        examEntity.setTableName(scoreTableName);
        Integer examId = examService.addExam(examEntity);
        if (examId != null){
            return Msg.success();
        }else {
            return Msg.fail(ErrorEnum.E_101,ErrorEnum.E_101.getErrorMsg());
        }
    }

    // 创建考试
    @DeleteMapping(value = "/delete")
    @ApiOperation(value = "删除考试")
    public Msg deleteExam(Integer examId){
        boolean result = examService.deleteExam(examId);
        if (result){
            return Msg.success();
        }else {
            return Msg.fail(ErrorEnum.E_101,ErrorEnum.E_101.getErrorMsg());
        }
    }

    // 查看当前老师需要录入那些考试的班级的成绩
    @GetMapping("/simpleExamList")
    @ApiOperation(value = "当前老师需要录入那些考试的班级的成绩")
    public Msg getSimpleExamList(){
        String teacherId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        List<SimpleExamEntity> examList = examService.listExamForCourseTeacher(teacherId);
        return Msg.success().add("examList", examList);
    }

    // 查看所有考试列表，用于查看考试班级的分数预览
    @GetMapping("/simpleAllExamList")
    @ApiOperation(value = "查看所有考试列表，用于查看考试班级的分数预览")
    public Msg ListAllSimpleExam(){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        List<SimpleExamEntity> examList = examService.findSimpleExamList(null, null ,schoolCode);
        return Msg.success().add("examList", examList);
    }

    //根据小程序的uId查询能看哪些从场次的考试
    @RequestMapping(value = "/weAppSimpleAllExamList" ,method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "examName", value = "考试名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "examTime", value = "考试时间", dataType = "String", paramType = "query"),
    })
    @ApiOperation(value = "根据小程序的uId查询能看哪些从场次的考试---教师的话不控制显示范围")
    public Msg getWeAppSimpleAllExamList(String uId, Integer currentPage, Integer pageSize, String examTime, String examName){
        // 3开头为家长，1开头为老师
        List<SimpleExamEntity> examList = new ArrayList<>();
        long totalCount = 0;
        if (pageSize == null || currentPage == null){
            currentPage = 1;
            pageSize = 10;
        }
        if(uId.startsWith("3")) {
            // 查询家长能够看哪些考试（自己的孩子的）
            PageHelper.startPage(currentPage, pageSize);
            examList = examService.listExamForParent(uId, examName, examTime);
            PageInfo<SimpleExamEntity> pageInfo = new PageInfo<>(examList);
            totalCount = pageInfo.getTotal();
        }else if (uId.startsWith("1")) {
            Integer schoolCode = userService.getSchoolCodeByUserId(uId);
            PageHelper.startPage(currentPage, pageSize);
            examList = examService.listSchoolExam(schoolCode, examName, examTime);
            PageInfo<SimpleExamEntity> pageInfo = new PageInfo<>(examList);
            totalCount = pageInfo.getTotal();
            for (SimpleExamEntity exam : examList) {
                exam.setClassList(examService.listExamClass(exam.getExamId()));
                exam.setCourseList(examService.listExamCourse(exam.getExamId()));
            }
        }
        for (SimpleExamEntity examEntity : examList) {
            // 查询每次考试的人数
            Integer examStudentCount = examService.countExamStudent(examEntity.getExamId());
            examEntity.setTotalCount(examStudentCount);
        }
        return Msg.success().add("examList", examList).add("totalCount", totalCount);
    }

    @GetMapping("/list-exam-class")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "查看所有考试的班级")
    public Msg ListExamClass(Integer examId){
        List<ClassEntity> examClassList = examService.listExamClass(examId);
        return Msg.success().add("examClassList", examClassList);
    }
}
